package com.StarStudio.Service.Impl;

import cn.hutool.core.util.IdUtil;
import com.StarStudio.DAO.GoodsStockDAO;
import com.StarStudio.Service.GoodsStockService;
import com.StarStudio.Service.RemoteSysUserService;
import com.ruoyi.common.core.Entity.GoodsStock;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class GoodsStockServiceImpl implements GoodsStockService {

    @Autowired
    GoodsStockDAO goodsStockDAO;

    @Autowired
    RemoteSysUserService remoteSysUserService;

    /**
     * 根据条件查询商品库存对象集合
     * @param goodsStock 商品库存对象
     * @return 商品库存集合
     */
    @Override
    public List<GoodsStock> findGoodsStockList(GoodsStock goodsStock) {
        SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
        if (sysUser.isAdmin()){
            List<GoodsStock> goodsStockList = goodsStockDAO.findGoodsStockList(goodsStock);
            if (goodsStockList != null && goodsStockList.size() > 0){
                for (GoodsStock stock : goodsStockList) {
                    SysUser sysUser1 = remoteSysUserService.getSysUserById(stock.getStore_id());
                    Map<String,Object> param = new HashMap<>();
                    param.put("storeName",sysUser1.getNickName());
                    stock.setParams(param);
                }
            }
            return goodsStockList;
        }
        List<GoodsStock> goodsStockListForNormalUser = goodsStockDAO.findGoodsStockListForNormalUser(goodsStock, sysUser.getUserId());
        if (goodsStockListForNormalUser != null && goodsStockListForNormalUser.size() > 0){
            for (GoodsStock stock : goodsStockListForNormalUser) {
                SysUser sysUser1 = remoteSysUserService.getSysUserById(stock.getStore_id());
                Map<String,Object> param = new HashMap<>();
                param.put("storeName",sysUser1.getNickName());
                stock.setParams(param);
            }
        }
        return goodsStockListForNormalUser;
    }

    /**
     * 新增商品库存数据
     * @param goodsStock 商品库存对象
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addGoodsStock(GoodsStock goodsStock) {
        goodsStock.setItem_id(IdUtil.getSnowflakeNextId()); //使用雪花ID
        goodsStock.setDel_flag(false);
        goodsStockDAO.addGoodsStock(goodsStock);
    }

    /**
     * 查询总记录数
     * @return 总记录数
     */
    @Override
    public long findAllRecordNumber() {
        return goodsStockDAO.findAllRecordNumber();
    }

    @Override
    public long findStoreAllRecordNumber(Long storeId) {
        return goodsStockDAO.findStoreAllRecordNumber(storeId);
    }
}
